package com.xuzimian.globaldemo.spring.security.oauth2.server.controller;


import com.xuzimian.globaldemo.spring.security.oauth2.server.util.ImageCodeHelper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.security.Principal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {
    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping("/logout")
    public String signout(HttpServletRequest request) throws Exception{
        request.logout();
        return "deny";
    }


    @PreAuthorize("isAnonymous()")
    @RequestMapping("/")
    public String index(){
        return "index";
    }


    @PreAuthorize("authenticated")
    @RequestMapping("/home")
    public String home(){
        return "index";
    }


    @RequestMapping(value = "/images/imagecode")
    public String imagecode(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        OutputStream os = response.getOutputStream();
        Map<String,Object> map = ImageCodeHelper.getImageCode(60, 20, os);

        String simpleCaptcha = "simpleCaptcha";
        request.getSession().setAttribute(simpleCaptcha, map.get("strEnsure").toString().toLowerCase());
        request.getSession().setAttribute("codeTime",new Date().getTime());

        try {
            ImageIO.write((BufferedImage) map.get("image"), "JPEG", os);
        } catch (IOException e) {
            return "";
        }
        return null;
    }

    @RequestMapping(value = "/checkcode")
    @ResponseBody
    public String checkcode(HttpServletRequest request, HttpSession session)
            throws Exception {
        String checkCode = request.getParameter("checkCode");
        Object simple = session.getAttribute("simpleCaptcha") ; //验证码对象
        if(simple == null){
            request.setAttribute("errorMsg", "验证码已失效，请重新输入！");
            return "验证码已失效，请重新输入！";
        }

        String captcha = simple.toString();
        Date now = new Date();
        Long codeTime = Long.valueOf(session.getAttribute("codeTime")+"");
        if(StringUtils.isEmpty(checkCode) || captcha == null ||  !(checkCode.equalsIgnoreCase(captcha))){
            request.setAttribute("errorMsg", "验证码错误！");
            return "验证码错误！";
        }else if ((now.getTime()-codeTime)/1000/60>5){//验证码有效长度为5分钟
            request.setAttribute("errorMsg", "验证码已失效，请重新输入！");
            return "验证码已失效，请重新输入！";
        }else {
            session.removeAttribute("simpleCaptcha");
            return "1";
        }
    }

    /**
     * 资源服务器测试接口，用法是为在localhost下登录时，采用访问资源服务器资源的方式访问该接口，不需要登录授权这一步骤，而是直接
     * 从access_token中解析出已授权的身份。如使用url访问受限资源方式：
     * http://localhost/api/user?access_token={jwt的值}
     *
     * 地址加/api前缀是为了防止Spring security web 的拦截url规则冲突。
     * 备注：授权服务拦截置顶的几个/oauth/token之类的url，Spring security web 拦截规则由WebSecurityConfigurerAdapter 的config方法设置，
     * 一般拦截除登录之外的所有url，所以会和资源服务器的拦截规则冲突。
     * @param puser
     * @return
     */
    @RequestMapping("/api/user")
    @ResponseBody
    public Map<String, Object> user(Principal puser) {

        Map<String, Object> userinfo = new HashMap<>();
        userinfo.put("id", "123");
        userinfo.put("name",puser.getName());
        userinfo.put("email", "516654313@qq.com");
        userinfo.put("department","董事会");
        userinfo.put("createdate", "2019-07-14");
        return userinfo;
    }
}
